package com.kinggm.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component("reentrantRedisLock")
public class ReentrantRedisLock implements RedisLock {

    private final String KEY_PREFIX = "REDIS_LOCK_";


    @Override
    public boolean tryLock(StringRedisTemplate stringRedisTemplate, String redisKey, String uuid, long timeoutSec) {
        // 定义lua表达式   /resource/lua 路径下有注释
        String scriptStr = "local key=KEYS[1];\n" +
                "local threadId = ARGV[1];\n" +
                "local releaseTime=ARGV[2];\n" +
                "if(redis.call('exists',key)== 0) then\n" +
                "    redis.call('hset', key, threadId, '1');\n" +
                "    redis.call(\"expire\", key, releaseTime);\n" +
                "    return 1;\n" +
                "end;\n" +
                "if(redis.call(\"hexists\",key,threadId)== 1) then\n" +
                "    redis.call(\"hincrby\", key, threadId, '1');\n" +
                "    redis.call(\"expire\", key, releaseTime);\n" +
                "    return 1;\n" +
                "end;\n" +
                "return 0;";
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setScriptText(scriptStr);
        script.setResultType(Long.class);
        Long result = stringRedisTemplate.execute(script, Collections.singletonList(KEY_PREFIX + redisKey), uuid, String.valueOf(timeoutSec));
        if (result == null) {
            return false;
        }
        return result == 1;
    }



    @Override
    public void releaseLock(StringRedisTemplate stringRedisTemplate, String redisKey, String uuid, long timeoutSec) {
        // 定义lua表达式   /resource/lua 路径下有注释
        String scriptStr = "local key=KEYS[1];\n" +
                "local threadId = ARGV[1];\n" +
                "local releaseTime=ARGV[2];\n" +
                "if(redis.call('HEXISTS',key,threadId)==0)then\n" +
                "    return nil;\n" +
                "end;\n" +
                "local count = redis.call('HINCRBY', key,threadId, -1);\n" +
                "if(count >0)then\n" +
                "    redis.call(\"EXPIRE\",key,releaseTime);\n" +
                "    return nil;\n" +
                "else\n" +
                "    redis.call('DEL', key);\n" +
                "    return nil;\n" +
                "end;";
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setScriptText(scriptStr);
        script.setResultType(Long.class);
        stringRedisTemplate.execute(script, Collections.singletonList(KEY_PREFIX + redisKey), uuid, String.valueOf(timeoutSec));
    }

    @Override
    public void releaseLock(StringRedisTemplate stringRedisTemplate, String redisKey, String uuid) {

    }


}
